/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.controller;

import io.renren.service.PackageInfo;
import io.renren.service.SysGeneratorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成器
 * 
 * @author Mark sunlightcs@gmail.com
 */
@Controller
@RequestMapping("/sys/generator")
@Api(tags = {"generator-API"}, description = "代码生成")
public class SysGeneratorController {
	@Autowired
	private SysGeneratorService sysGeneratorService;
	
	/**
	 * 生成代码
	 */
	@ApiOperation(value = "代码生成", notes = "代码生成", httpMethod = "GET")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "tables", value = "表名，多个则英文逗号间隔", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "packageName", value = "包名，如 com.yhyouhu.carservice", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "moduleName", value = "模块名，如 productConfig", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "hasTenant", value = "是否包含租户，0-不包含，其他包含", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "author", value = "作者，备注使用", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "desc", value = "备注说明", dataType = "String", paramType = "query")
	})
	@RequestMapping("/code")
	public void code(@RequestParam String tables, @RequestParam String packageName, @RequestParam String moduleName, @RequestParam String hasTenant
			,@RequestParam String author, @RequestParam(required = false) String desc, HttpServletResponse response) throws IOException{
		PackageInfo packageInfo = new PackageInfo(packageName, moduleName, author, desc, hasTenant);
		byte[] data = sysGeneratorService.generatorCode(tables.split(","), packageInfo);
		
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"system-code.zip\"");
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}
}
